package cn.itcast.xuesheng.dao.impl;

import cn.itcast.xuesheng.dao.UserDao;
import cn.itcast.xuesheng.domain.User;
import cn.itcast.xuesheng.utils.JdbcUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("userDao")
public class UserDaoImpl implements UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public User isLogin(User LoginUser) {
        try {
            String sql = "SELECT * FROM user WHERE username = ? AND password = ?";
            User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), LoginUser.getUsername(), LoginUser.getPassword());
            return user;
        } catch (DataAccessException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void insert(User user) {
        String sql = "insert into user (username,password,job) value(?,?,?)";
        jdbcTemplate.update(sql, user.getUsername(), user.getPassword(), user.getJob());
    }

    @Override
    public User check(String username) {
        try {
            String sql="SELECT * FROM user WHERE username=?";
            User user1 = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class),username);
            return user1;
        }
        catch (Exception e){
            return null;
        }

    }
    public void update(User user){
        String sql1="UPDATE user SET password = ? WHERE username=?";
        String sql2="UPDATE user SET job = ? WHERE username=?";
        jdbcTemplate.update(sql1,user.getPassword(),user.getUsername());
        jdbcTemplate.update(sql2,user.getJob(),user.getUsername());
    }

    @Override
    public void delete(int tid) {
        String sql="DELETE FROM topic WHERE tid=?";
        jdbcTemplate.update(sql,tid);
    }

    @Override
    public List<User> findAll() {
        return null;
    }

}
